package com.SY7DA.UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import android.util.Log;

public class UDPServer implements Runnable {  
	  
	    private static final int PORT = 6543;  
	  
	    private byte[] msg = new byte[1024];  
	  
	    private boolean life = true;  
	 
	    public UDPServer() {  
	   }  
	  
	    /** 
	    * @return the life 
	     */  
	   public boolean isLife() {  
	        return life;  
	    }  
	  
	    /** 
	     * @param life 
	     *            the life to set 
	     */  
	    public void setLife(boolean life) {  
	        this.life = life;  
	    }  
	  
	    public int count=0;
	   @Override  
	    public void run() {  
	        DatagramSocket dSocket = null;  
	        DatagramPacket dPacket = new DatagramPacket(msg, msg.length);  
	        try {  
	            dSocket = new DatagramSocket(PORT);  
	           while (life) {  
	                try {  
	                	count++;
	                    dSocket.receive(dPacket);   
	                    String data = new String(dPacket.getData());
	                    data = data.substring(0,dPacket.getLength());
	                    Log.i("msg sever received",data);  
	                    
	                    if(data.equals("a"))
	                    {
	                    	InetAddress address = dPacket.getAddress();
	                    	int port = dPacket.getPort();
	                    	String message = "R";
		         	        DatagramPacket dPacketClient = new DatagramPacket(message.getBytes(), 
		         	        		   message.length(),address,port); 
	                    	
	         	          dSocket.send(dPacketClient);
	                    	
	                    }
	                    
	               } catch (IOException e) {  
	                   e.printStackTrace();  
	                }  
	           }  
	        } catch (SocketException e) {  
	            e.printStackTrace();  
	        }  
	    }  
	}  
